# @Author: huguangzhi
# @design: E480
# @ContactEmail : huguangzhi@ucsdigital.com.com
# @ContactPhone : 13121961510
# @Desc  :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import ast
import json
import time
from io import BytesIO
from random import random

import requests
from PIL import Image, ImageDraw

headers = {
    'Connection': "keep-alive" ,
    'sec-ch-ua':'"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"' ,
    'Accept' :'application/json, text/plain, */*' ,
    'X-Client-Type':"pc" ,
    'sec-ch-ua-mobile': "?0" ,
    'User-Agent':"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36" ,
    'Content-Type':'application/json' ,
    'Origin':'https://www.bjjnts.cn' ,
    'Sec-Fetch-Site':'same-site' ,
    'Sec-Fetch-Mode':'cors' ,
    'Sec-Fetch-Dest':'empty' ,
    'Referer':'https://www.bjjnts.cn/user/login',
    'Accept-Language':'zh-CN,zh;q=0.9,en;q=0.8'
}

def create_req(method="POST",headers=headers, others=None, url=None):
    session = requests.session()
    if method == "POST":
        resp = session.post(url= url, data=json.dumps(others), headers=headers)
        if resp.status_code == 200:
            req = resp.text.replace("null", "None")
        elif resp.status_code == 201:
            req = resp.text.replace("null", "None")
        else:
            return resp.text
    if method == "GET":

        resp = session.get(url=url, headers=headers)
        if resp.status_code == 200:
            req = resp.text.replace("null", "None")
        else:
            return resp.text
    time.sleep(1)
    return ast.literal_eval(req)


def getUserClass(accessToken:str):
    url = 'https://apif.bjjnts.cn/student-center/study'
    other_header = {
        "Authorization": "Bearer "+ accessToken,
        "Refer":"https://www.bjjnts.cn/mine/student/study"
    }
    headers.update(other_header)
    resp = create_req(method="GET", headers=headers, url=url)
    data = [
        {
            'id': '2079622',
             'class_id': '86055',
             'uid': '11863425',
             'exam_score': '0',
             'practice_score': '0',
             'create_time': '1635836435',
             'is_exam_score': '0',
             'is_practice_score': '0',
             'type': '1',
             'subsidy': '0',
             'labour': '2',
             'group_id': '0',
             'is_questionnaire': '0',
             'questionnaire_time': '0',
             'contract_start_time': '1626364800',
             'contract_end_time': '1689350400',
             'status': '1',
             'invalid_remark': '',
             'cer_code': '',
             'frontendClass': {
                'id': '86055',
                 'name': '清华附小1班',
                 'create_user': '10272708',
                 'course_category': '0',
                 'type': '1',
                 'course_time': '0',
                 'course_period': '81.1',
                 'status': '2',
                 'policy_id': '1',
                 'start_time': '1635836695',
                 'statusName': {
                    'key': '2',
                     'name': '进行中'
                },
                 'typeName': {
                    'key': '1',
                     'name': '线上培训+线下培训'
                },
                 'createUser': {
                    'id': '10272708',
                     'name': '中企基业(北京)管理顾问有限公司',
                     'avatar': '',
                     'email': '1073689273@qq.com'
                },
                 'policyInfo': {
                    'id': '1',
                     'title': '以训兴业',
                     'study_publish': '2',
                     'unit': '2',
                     'test_type': '1',
                     'student_type': '2',
                     'staff_type': '1',
                     'coupons_support': '2'
                },
                 'ladder': [

                ]
            },
             'courseMap': [
                {
                    'id': '16994317',
                     'class_id': '86055',
                     'uid': '11863425',
                     'course_id': '917',
                     'type': '1',
                     'create_time': '1635836537',
                     'score': '0',
                     'status': '1',
                     'courseType': {
                        'key': '1',
                         'name': '点播课'
                    },
                     'course': {
                        'id': '917',
                         'bid': '1055',
                         'title': '职业生涯规划',
                         'image': 'https://zpimg.cn/b//20210623/60d2f2baebca9.png?x-oss-process=image/resize,m_fill,h_450,w_800,limit_0',
                         'total_period': '7.4',
                         'total_time': '20027',
                         'total_video': '7',
                         'map': [
                            {
                                'cid': '2',
                                 'course_id': '917',
                                 'category': {
                                    'id': '2',
                                     'name': ' 岗前培训',
                                     'level': '2',
                                     'pid': '1',
                                     'is_last': '1'
                                }
                            },
                             {
                                'cid': '1',
                                 'course_id': '917',
                                 'category': {
                                    'id': '1',
                                     'name': '通用素质',
                                     'level': '1',
                                     'pid': '0',
                                     'is_last': '0'
                                }
                            }
                        ],
                         'source': {
                            'id': '1055',
                             'name': '北京企点时代科技有限公司',
                             'avatar': 'https://zpimg.cn/bj/img/20210624/60d3ff1207507.png',
                             'seller': {
                                'uid': '1055',
                                 'contact_name': '兰宏凯',
                                 'contact_mobile': '4006900708',
                                 'company_name': '腾讯云计算（北京）有限责任公司',
                                 'company_contact': '兰宏凯',
                                 'company_alias_name': '腾讯乐享'
                            }
                        }
                    },
                     'progress': 0.0977
                },
                 {
                    'id': '16994307',
                     'class_id': '86055',
                     'uid': '11863425',
                     'course_id': '926',
                     'type': '1',
                     'create_time': '1635836537',
                     'score': '0',
                     'status': '1',
                     'courseType': {
                        'key': '1',
                         'name': '点播课'
                    },
                     'course': {
                        'id': '926',
                         'bid': '1055',
                         'title': '文书处理与公共关系',
                         'image': 'https://zpimg.cn/b//20210623/60d2f2d0dcccb.png?x-oss-process=image/resize,m_fill,h_450,w_800,limit_0',
                         'total_period': '4.1',
                         'total_time': '11151',
                         'total_video': '4',
                         'map': [
                            {
                                'cid': '2',
                                 'course_id': '926',
                                 'category': {
                                    'id': '2',
                                     'name': ' 岗前培训',
                                     'level': '2',
                                     'pid': '1',
                                     'is_last': '1'
                                }
                            },
                             {
                                'cid': '1',
                                 'course_id': '926',
                                 'category': {
                                    'id': '1',
                                     'name': '通用素质',
                                     'level': '1',
                                     'pid': '0',
                                     'is_last': '0'
                                }
                            }
                        ],
                         'source': {
                            'id': '1055',
                             'name': '北京企点时代科技有限公司',
                             'avatar': 'https://zpimg.cn/bj/img/20210624/60d3ff1207507.png',
                             'seller': {
                                'uid': '1055',
                                 'contact_name': '兰宏凯',
                                 'contact_mobile': '4006900708',
                                 'company_name': '腾讯云计算（北京）有限责任公司',
                                 'company_contact': '兰宏凯',
                                 'company_alias_name': '腾讯乐享'
                            }
                        }
                    },
                     'progress': 0.052
                },
                 {
                    'id': '16994297',
                     'class_id': '86055',
                     'uid': '11863425',
                     'course_id': '1086',
                     'type': '1',
                     'create_time': '1635836537',
                     'score': '0',
                     'status': '1',
                     'courseType': {
                        'key': '1',
                         'name': '点播课'
                    },
                     'course': {
                        'id': '1086',
                         'bid': '1055',
                         'title': '先认识自我再适应职场',
                         'image': 'https://zpimg.cn/b//20210630/60dbdab7e1a32.png?x-oss-process=image/resize,m_fill,h_450,w_800,limit_0',
                         'total_period': '25.5',
                         'total_time': '69025',
                         'total_video': '21',
                         'map': [
                            {
                                'cid': '6',
                                 'course_id': '1086',
                                 'category': {
                                    'id': '6',
                                     'name': '职业礼仪',
                                     'level': '2',
                                     'pid': '1',
                                     'is_last': '1'
                                }
                            },
                             {
                                'cid': '1',
                                 'course_id': '1086',
                                 'category': {
                                    'id': '1',
                                     'name': '通用素质',
                                     'level': '1',
                                     'pid': '0',
                                     'is_last': '0'
                                }
                            }
                        ],
                         'source': {
                            'id': '1055',
                             'name': '北京企点时代科技有限公司',
                             'avatar': 'https://zpimg.cn/bj/img/20210624/60d3ff1207507.png',
                             'seller': {
                                'uid': '1055',
                                 'contact_name': '兰宏凯',
                                 'contact_mobile': '4006900708',
                                 'company_name': '腾讯云计算（北京）有限责任公司',
                                 'company_contact': '兰宏凯',
                                 'company_alias_name': '腾讯乐享'
                            }
                        }
                    },
                     'progress': 0.0343
                },
                 {
                    'id': '16994287',
                     'class_id': '86055',
                     'uid': '11863425',
                     'course_id': '1194',
                     'type': '1',
                     'create_time': '1635836537',
                     'score': '0',
                     'status': '1',
                     'courseType': {
                        'key': '1',
                         'name': '点播课'
                    },
                     'course': {
                        'id': '1194',
                         'bid': '1055',
                         'title': '细说职业素养',
                         'image': 'https://zpimg.cn/b//20210630/60dc4b83262ef.png?x-oss-process=image/resize,m_fill,h_450,w_800,limit_0',
                         'total_period': '44.0',
                         'total_time': '118982',
                         'total_video': '52',
                         'map': [
                            {
                                'cid': '6',
                                 'course_id': '1194',
                                 'category': {
                                    'id': '6',
                                     'name': '职业礼仪',
                                     'level': '2',
                                     'pid': '1',
                                     'is_last': '1'
                                }
                            },
                             {
                                'cid': '1',
                                 'course_id': '1194',
                                 'category': {
                                    'id': '1',
                                     'name': '通用素质',
                                     'level': '1',
                                     'pid': '0',
                                     'is_last': '0'
                                }
                            }
                        ],
                         'source': {
                            'id': '1055',
                             'name': '北京企点时代科技有限公司',
                             'avatar': 'https://zpimg.cn/bj/img/20210624/60d3ff1207507.png',
                             'seller': {
                                'uid': '1055',
                                 'contact_name': '兰宏凯',
                                 'contact_mobile': '4006900708',
                                 'company_name': '腾讯云计算（北京）有限责任公司',
                                 'company_contact': '兰宏凯',
                                 'company_alias_name': '腾讯乐享'
                            }
                        }
                    },
                     'progress': 0.6953
                }
            ],
             'satisfied': 0,
             'demand': 0,
             'progress': 0.3913
        }
    ]

    if resp[0]["progress"] > 0.9999:
        return []
    return resp[0]["courseMap"]


def getUserInfo(user:dict):
    url = "https://apif.bjjnts.cn/account/login"
    data = {
        "username": user["username"],
        "password": user["password"],
        "type": 1
    }
    headers.update({"Referer": "https://www.bjjnts.cn/user/login"})

    userinfo = create_req("POST", headers, data, url)

    return userinfo


def getUserTopic(accessToken:str, courseID:str, classID:str):
    url = "https://apif.bjjnts.cn/courses/test-preview?course_id={}&class_id={}".format(courseID, classID)

    other_header = {
        "Authorization": "Bearer " + accessToken,
        "Refer": "https://www.bjjnts.cn/study?course_id={}&class_id={}".format(courseID, classID)
    }

    headers.update(other_header)
    resp = create_req(method="GET", headers=headers, url=url)
    # '''
    data = {'is_task': 1, 'course': [
        {'id': '4668', 'course_id': '917', 'title': '第一章如何快速了解市场行情', 'description': '', 'sort': '1', 'hide': '0',
         'create_time': '1624460392', 'update_time': '1624460392', 'sections': None, 'units': [
            {'id': '14644', 'bid': '1055', 'open_id': '194117', 'chapter_id': '4668', 'section_id': '0', 'type': '1',
             'title': '如何快速了解市场行情', 'description': '', 'total_time': '2962', 'total_question': '0', 'sort': '1',
             'hide': '0', 'create_time': '1624437721', 'update_time': '1624437722', 'is_see': '0',
             'typeName': {'key': '1', 'name': '视频'}, 'files': [], 'order_number': '', 'train': None, 'lastTrain': None,
             'unitMap': None, 'lastUnitId': 0, 'progress_time': 600, 'progress': 0.2026}], 'order_number': ''},
        {'id': '4669', 'course_id': '917', 'title': '第二章职业生涯规划的价值', 'description': '', 'sort': '2', 'hide': '0',
         'create_time': '1624460392', 'update_time': '1624460392', 'sections': None, 'units': [
            {'id': '14645', 'bid': '1055', 'open_id': '194118', 'chapter_id': '4669', 'section_id': '0', 'type': '1',
             'title': '职业生涯规划的价值', 'description': '', 'total_time': '2905', 'total_question': '0', 'sort': '1',
             'hide': '0', 'create_time': '1624437724', 'update_time': '1624437725', 'is_see': '0',
             'typeName': {'key': '1', 'name': '视频'}, 'files': [], 'order_number': '', 'train': None, 'lastTrain': None,
             'unitMap': None, 'lastUnitId': 1, 'progress_time': 360, 'progress': 0.1239}], 'order_number': ''},
        {'id': '4670', 'course_id': '917', 'title': '第三章职业规划必经的阶段', 'description': '', 'sort': '3', 'hide': '0',
         'create_time': '1624460392', 'update_time': '1624460392', 'sections': None, 'units': [
            {'id': '14646', 'bid': '1055', 'open_id': '194119', 'chapter_id': '4670', 'section_id': '0', 'type': '1',
             'title': '职业规划必经的阶段', 'description': '', 'total_time': '2843', 'total_question': '0', 'sort': '1',
             'hide': '0', 'create_time': '1624437728', 'update_time': '1624437729', 'is_see': '0',
             'typeName': {'key': '1', 'name': '视频'}, 'files': [], 'order_number': '', 'train': None, 'lastTrain': None,
             'unitMap': None, 'lastUnitId': 0, 'progress_time': 240, 'progress': 0.0844}], 'order_number': ''},
        {'id': '4671', 'course_id': '917', 'title': '第四章如何定制职业计划书', 'description': '', 'sort': '4', 'hide': '0',
         'create_time': '1624460392', 'update_time': '1624460392', 'sections': None, 'units': [
            {'id': '14647', 'bid': '1055', 'open_id': '194120', 'chapter_id': '4671', 'section_id': '0', 'type': '1',
             'title': '如何定制职业计划书', 'description': '', 'total_time': '2704', 'total_question': '0', 'sort': '1',
             'hide': '0', 'create_time': '1624437732', 'update_time': '1624437733', 'is_see': '0',
             'typeName': {'key': '1', 'name': '视频'}, 'files': [], 'order_number': '', 'train': None, 'lastTrain': None,
             'unitMap': None, 'lastUnitId': 0, 'progress_time': 240, 'progress': 0.0888}], 'order_number': ''},
        {'id': '4672', 'course_id': '917', 'title': '第五章职业生涯规划-理想和现实哪个更重要一', 'description': '', 'sort': '5',
         'hide': '0', 'create_time': '1624460392', 'update_time': '1624460392', 'sections': None, 'units': [
            {'id': '14648', 'bid': '1055', 'open_id': '194121', 'chapter_id': '4672', 'section_id': '0', 'type': '1',
             'title': '职业生涯规划-理想和现实哪个更重要一', 'description': '', 'total_time': '2775', 'total_question': '0', 'sort': '1',
             'hide': '0', 'create_time': '1624437735', 'update_time': '1624437736', 'is_see': '0',
             'typeName': {'key': '1', 'name': '视频'}, 'files': [], 'order_number': '', 'train': None, 'lastTrain': None,
             'unitMap': None, 'lastUnitId': 0, 'progress_time': 240, 'progress': 0.0865}], 'order_number': ''},
        {'id': '4673', 'course_id': '917', 'title': '第六章职业生涯规划-理想和现实哪个更重要二', 'description': '', 'sort': '6',
         'hide': '0', 'create_time': '1624460392', 'update_time': '1624460392', 'sections': None, 'units': [
            {'id': '14649', 'bid': '1055', 'open_id': '194123', 'chapter_id': '4673', 'section_id': '0', 'type': '1',
             'title': '职业生涯规划-理想和现实哪个更重要二', 'description': '', 'total_time': '2775', 'total_question': '0', 'sort': '1',
             'hide': '0', 'create_time': '1624437739', 'update_time': '1624437740', 'is_see': '0',
             'typeName': {'key': '1', 'name': '视频'}, 'files': [], 'order_number': '', 'train': None, 'lastTrain': None,
             'unitMap': None, 'lastUnitId': 0, 'progress_time': 240, 'progress': 0.0865}], 'order_number': ''},
        {'id': '4674', 'course_id': '917', 'title': '第七章职业生涯规划-理想和现实哪个更重要三', 'description': '', 'sort': '7',
         'hide': '0', 'create_time': '1624460392', 'update_time': '1624460392', 'sections': None, 'units': [
            {'id': '14650', 'bid': '1055', 'open_id': '194124', 'chapter_id': '4674', 'section_id': '0', 'type': '1',
             'title': '职业生涯规划-理想和现实哪个更重要三', 'description': '', 'total_time': '3063', 'total_question': '0', 'sort': '1',
             'hide': '0', 'create_time': '1624437742', 'update_time': '1624437743', 'is_see': '0',
             'typeName': {'key': '1', 'name': '视频'}, 'files': [], 'order_number': '', 'train': None, 'lastTrain': None,
             'unitMap': None, 'lastUnitId': 0, 'progress_time': 420, 'progress': 0.1371}], 'order_number': ''}],
            'test': {'id': '918', 'bid': '1055', 'course_id': '917', 'title': '职业生涯规划课后考试', 'time': '3600',
                     'publish_status': '0', 'create_time': '1624460388', 'update_time': '1624460388',
                     'delete_status': '0', 'open_id': '930'}, 'is_test': 2}
    # '''
    return resp


def getMovieInfo(accessToken:str, classID:str, unitID:str, courseID:str):
    url = "https://apif.bjjnts.cn/course-units/{}?class_id={}".format(unitID, classID)
    other_header = {
        "Authorization": "Bearer " + accessToken,
        "Refer": "https://www.bjjnts.cn/study/video?class_id={}&course_id={}&unit_id={}".format( classID, courseID, unitID)
    }

    headers.update(other_header)

    data = {
        'id': '14644',
        'bid': '1055',
        'open_id': '194117',
        'chapter_id': '4668',
        'section_id': '0',
        'type': '1',
        'title': '如何快速了解市场行情',
        'description': '',
        'total_time': '2962',
        'total_question': '0',
        'sort': '1',
        'hide': '0',
        'create_time': '1624437721', 'update_time': '1624437722', 'is_see': '0', 'typeName': {'key': '1', 'name': '视频'},
        'chapter':
            {'id': '4668',
             'title': '第一章如何快速了解市场行情',
             'course_id': '917'},
        'section': None, 'files': [],
        'unitMap': None, 'train': None, 'lastTrain': None,
        'video': {'id': '14585', 'open_id': '189165', 'course_id': '917', 'unit_id': '14644', 'type': '4', 'image': '',
                  'description': '',
                  'url': 'https://1252005255.vod2.myqcloud.com/d76f99davodgzp1252005255/e33849133701925918787748404/zfFnWrwTgRYA.mp4',
                  'vod_id': '',
                  'time': '2962',
                  'size': '0',
                  'total_url': '0',
                  'status': '2',
                  'sort': '1',
                  'hide': '0',
                  'create_time': '1624437722',
                  'update_time': '1624437722',
                  'remarks': '',
                  'urls': [
                      {'id': '26007',
                       'video_id': '14585',
                       'clarity': '3',
                       'type': '0',
                       'url': 'https://1252005255.vod2.myqcloud.com/8b973c82vodtransgzp1252005255/e33849133701925918787748404/v.f875.mp4?t=619a6b98&us=oxgnfjfabw&sign=fb5a7f9ddc045a2e1ca8ec209bfa2064&wf=bj.pc',
                       'resolution_width': '0',
                       'resolution_height': '0',
                       'bit': '0.0000',
                       'size': '0',
                       'source_id': 'f0e4b588c40d11ebbbea26517d29f512',
                       'clarityName': {
                           'key': '3',
                           'name': '高清'
                       }
                       }
                  ]
                  },
        'progress_time': 600,
        'progress': 0.2026,
        'is_task': 1, 'course_id': '917', 'class_id': 86055,
        'unit_id': '14644'}

    '''
       '''
    resp = create_req(method="GET", headers=headers, url=url)

    movieinfo = {
        "class_id": classID,
        "course_id": resp["video"]["course_id"],
        "unit_id": resp["video"]["unit_id"],
        "video_id": resp["video"]["id"],
        "time": resp["video"]["time"],
        "progress_time": resp["progress_time"],
        'chapter': resp['chapter']["title"]
    }

    # return resp
    return movieinfo


def run_study(studyInfo:dict, accessToken:str, isEnd= False):
    study_info = studyInfo
    url = "https://apif.bjjnts.cn/studies?video_id={}&u={}&time={}&unit_id={}&class_id={}".format(
        study_info["video_id"],
        study_info["user_id"],
        study_info["time"],
        study_info["unit_id"],
        study_info["class_id"]
    )
    if studyInfo["time"] == 0:
        url += "&start=1"

    if isEnd :
        url += "&end=1"

    other_header = {
        "Authorization": "Bearer " + accessToken,
        "Refer": "https://www.bjjnts.cn/study/video?class_id={}&course_id={}&unit_id={}".format(studyInfo["class_id"],
                                                                                                studyInfo["course_id"],
                                                                                                studyInfo["unit_id"])
    }
    headers.update(other_header)

    resp_s = create_req(method="POST", headers=headers, url=url)
    print(resp_s, end="")
    resp = ast.literal_eval(str(resp_s))

    # resp = '{"name": "Forbidden", "message": "请人机验证", "code": 2002, "status": 403}'
    # 注意这里要出现人机验证了
    if resp.get("code", 0) == 2002:
        print("2002 人机验证")
        print(smart(accessToken, studyInfo))
    elif resp.get("code", 0) == 2003:
        print("2003 人脸识别")
        print(face(accessToken, studyInfo))

    if resp.get("video_time") != int(resp.get("count_time")):
        print("完成一轮，等待60秒")
        time.sleep(60)
        return run_study(study_info, accessToken)
    # if resp.get("video_time", 0) != 0:
    #     if int(resp["video_time"]) < int(resp['count_time']) -60:
    #         study_info["time"] = resp["video_time"]
    #         return run_study(study_info, accessToken)
    return resp


def smart(accessToken, studyInfo):
    "人机验证"
    url = "https://apif.bjjnts.cn/supervises/smart"

    data = {
        "course_id": studyInfo["course_id"],
        "unit_id": studyInfo["unit_id"],
        "class_id": studyInfo["class_id"]
    }
    other_header = {
        "Authorization": "Bearer " + accessToken,
        "Refer": "https://www.bjjnts.cn/study/video?class_id={}&course_id={}&unit_id={}".format(studyInfo["class_id"],
                                                                                                studyInfo["course_id"],
                                                                                                studyInfo["unit_id"])
    }
    headers.update(other_header)

    resp = create_req(method="POST", headers=headers, others=data, url=url)
    return resp


def face(accessToken, studyInfo):
    url = "https://apif.bjjnts.cn/supervises/smart"
    data = {
        "baseImage": str(faceImage()),
        "course_id": studyInfo["course_id"],
        "unit_id": studyInfo["unit_id"],
        "class_id": studyInfo["class_id"]
    }
    other_header = {
        "Authorization": "Bearer " + accessToken,
        "Refer": "https://www.bjjnts.cn/study/video?class_id={}&course_id={}&unit_id={}".format(studyInfo["class_id"],
                                                                                                studyInfo["course_id"],
                                                                                                studyInfo["unit_id"])
    }
    headers.update(other_header)
    resp = create_req(method="POST", headers=headers, others=data, url=url)
    return resp


def faceImage(userID="18515581600"):
    img_path = './{}.jpg'.format(userID)
    # 从内存中读图片
    content = open(img_path, 'rb').read()
    img = Image.open(BytesIO(content))
    draw = ImageDraw.Draw(img)
    draw.text((int(random()*287), int(random()*287)), str(int(random()*100)), fill=(0, 0, 0))
    return img

    # 往内存中写图片
    img = Image.open(img_path)
    with BytesIO() as out:
        img.save(out, format='JPEG')
        with open('out_stream.jpg', 'wb') as fo:
            fo.write(out.getvalue())


def execTask(needData:dict):
    movieInfo = getMovieInfo(
        accessToken=needData["access_token"],
        classID=needData["classID"],
        unitID=needData["unitID"],
        courseID=needData["courseID"]
    )
    movieInfo.update({"user_id": needData["user_id"], })

    print("-" * 10)
    time.sleep(50)
    print("userUnits {}/{}".format(index, len(userUnits)))
    print("{}共计{}已经完成{}".format(movieInfo["chapter"],movieInfo["time"],movieInfo["progress_time"]))
    print("-" * 10)

    # 开始学习

    study_stat = run_study(studyInfo=movieInfo, accessToken=userinfo["access_token"])


def schedleTask():
    pass




if __name__ == '__main__':

    user = {
        "username": "18515581600",
        "password": "18515581600"
    }
    userinfo = getUserInfo(user)
    print(userinfo)
    # userinfo = {
    #     "access_token": 'R6CDSCylLIZ6TpBn_oRVG7XeNA7ZPA5W-1637498065',
    #     "id": 11863425
    #             }
    # # print(userinfo)

    userCourseMap = getUserClass(accessToken=userinfo["access_token"])
    print("#"*30)
    # print(userCourseMap)
    # print("-"*10)
    # print("userCourseMap")
    # print("-"*10)

    # 我们只需要courseMap,里面包含了courseID和classID
    # userCourseMap = [
    #     {
    #         "class_id": '86055',
    #         "course_id": '917'
    #     }, {
    #         "class_id": '86055',
    #         "course_id": '926'
    #     }, {
    #         "class_id": '86055',
    #         "course_id": '1086'
    #     }, {
    #         "class_id": '86055',
    #         "course_id": '1194'
    #     }
    # ]

    # 获取章节units,只要course.units的数据
    for index, item in enumerate(userCourseMap):
        userUnits = getUserTopic(accessToken=userinfo["access_token"],
                                 courseID=item["course_id"],
                                 classID=item["class_id"])["course"]

        print("-" * 10)
        # print(item)
        print("userCourseMap {}/{}".format(index, len(userCourseMap)), end="")
        print("{}完成进度{}".format(item["course"]["title"],item["progress"]))

        print("-" * 10)

        # userUnits = [
        #     {"units": [{"id": 4668}]},
        #     {"units": [{"id": 4669}]},
        #     {"units": [{"id": 4670}]},
        #     {"units": [{"id": 4671}]},
        #     {"units": [{"id": 4672}]},
        #     {"units": [{"id": 4673}]},
        #     {"units": [{"id": 4674}]}
        # ]
        #
        # print(userUnits)

        for index, unit in enumerate(userUnits):

            datas = {'id': '4671', 'course_id': '917', 'title': '第四章如何定制职业计划书', 'description': '', 'sort': '4',
                     'hide': '0',
                     'create_time': '1624460392', 'update_time': '1624460392', 'sections': None,
                     'units': [
                    {'id': '14647', 'bid': '1055', 'open_id': '194120', 'chapter_id': '4671', 'section_id': '0',
                     'type': '1',
                     'title': '如何定制职业计划书', 'description': '', 'total_time': '2704', 'total_question': '0', 'sort': '1',
                     'hide': '0', 'create_time': '1624437732', 'update_time': '1624437733', 'is_see': '0',
                     'typeName': {'key': '1', 'name': '视频'}, 'files': [], 'order_number': '', 'train': None,
                     'lastTrain': None,
                     'unitMap': None, 'lastUnitId': 0, 'progress_time': 240, 'progress': 0.0888}], 'order_number': ''}
            if unit["units"][0]["progress"] > 0.9999:
                continue
            # print(unit)
            knowinfo = [
                unit["units"][0]["title"],
                unit["units"][0]["progress"],
            ]
            needData = {
                "access_token":userinfo["access_token"],
                "classID": item["class_id"],
                "unitID":unit["units"][0]["id"],
                "courseID":item["course_id"],
                "user_id": userinfo["id"]
            }

            study_stat = execTask(needData)

            # if int(study_stat.get("video_time")) < int(study_stat.get("count_time")):
            #     pass


        print("#"*20)
    print("#"*20)



